package com.jiaai.filter.aop;


import com.jiaai.auth.model.AccessUser;
import com.jiaai.auth.util.JWTEncryptUtil;
import com.jiaai.exception.ErrorCode;
import com.jiaai.util.ConstantUtils;
import com.jiaai.util.RestResultGenerator;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * class_name:TokenAspect
 * describe:------------------>token拦截切面
 * create_user:张昉平
 * create_date:2018/2/6
 * create_time:12:51
 */
@Aspect
@Component
public class TokenAspect {

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(token)")
    public Object around(ProceedingJoinPoint jp, TokenIntercept token) throws Throwable {
        String tokens = request.getHeader("Authorization");
        if(StringUtils.isEmpty(tokens)){
                return RestResultGenerator.genErrorResult(ErrorCode.IS_TOKEN_INVALID,"token 过期");
        }else{
            AccessUser user = null;
            try {
                user = JWTEncryptUtil.decrypt(tokens);
                boolean checkVisitor = token.checkVisitor();
                if (checkVisitor){
                    if (user.isVisitor()){
                        return RestResultGenerator.genErrorResult(300004,"游客禁止访问");
                    }
                }
                request.getSession().setAttribute(ConstantUtils.ACCESS_USER,user);
            }catch (Exception e){
                return RestResultGenerator.genErrorResult(ErrorCode.IS_TOKEN_INVALID,"token 过期");
            }
        }
        return jp.proceed();
    }
}
